package com.hy.z.config;

import com.alibaba.fastjson.JSONObject;
import com.hy.z.result.Result;
import com.hy.z.shiro.JwtToken;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description: 自定义认证过滤器
 * @author: FengHongYun
 * @Version: 1.0
 * @CreatedDate: 2020/3/6 14:47
 * @return
 **/
@Slf4j
public class AuthFilter extends AccessControlFilter {

    @Override
    protected boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse servletResponse, Object o) {

        return false;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws IOException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.setContentType("text/json;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        String token = request.getHeader("token");
        JwtToken jwtToken = new JwtToken(token);
        try {
            Subject subject = SecurityUtils.getSubject();
            subject.login(jwtToken);
            return true;
        } catch (AuthenticationException e) {
            //"认证失败!原因: "+
            Map<String, Object> map = new HashMap<>();
            map.put("code",12015);
            map.put("msg","error");
            map.put("info",e.getMessage());
            response.getWriter().println(new JSONObject(map));
        }
        return false;
    }

}
